package com.seari.service;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.seari.bean.DaduhuiBean;
import com.seari.bean.DaduhuiDataBean;
import com.seari.commonutils.redis.JedisUtilProxy;
import com.seari.controller.MetroDataController;

import redis.clients.jedis.Jedis;

@Service
public class DaduhuiDataServiceImpl implements DaduhuiDataService
{
	@Autowired
	private AppCacheService appCacheService;

	@Override
	public void setFlowdata(DaduhuiBean daduhuiBean)
	{
		// TODO Auto-generated method stub
		Jedis jedis = null;
		try
		{
			jedis = JedisUtilProxy.getJedis();
			HashMap<String, DaduhuiDataBean> resultMap = convertBeanToMap(daduhuiBean);
			HashMap<String, String> resultMapOfString = new HashMap<>();
			for (Entry<String, DaduhuiDataBean> entry : resultMap.entrySet())
			{
//				resultMapOfString.put(entry.getKey(), new String(JSON.toJSONString(entry.getValue()).getBytes(Charset.forName("UTF-8"))));
				resultMapOfString.put(entry.getKey(), JSON.toJSONString(entry.getValue()));
			}
			jedis.hmset(MetroDataController.METRO_FLOW_KEY, resultMapOfString);
		} catch (Exception e)
		{
			// TODO: handle exception
			e.printStackTrace();
		}finally {
			JedisUtilProxy.close(jedis);
		}
	}
	
	public HashMap<String, DaduhuiDataBean> convertBeanToMap(DaduhuiBean daduhuiBean)
	{
		HashMap<String, DaduhuiDataBean> resultMap = new HashMap<>();
		@SuppressWarnings("unchecked")
		HashMap<String, DaduhuiDataBean> cacheMap = (HashMap<String, DaduhuiDataBean>) appCacheService.getCacheObject(MetroDataController.METRO_FLOW_KEY);
		for (DaduhuiDataBean bean : daduhuiBean.getData())
		{
			//添加至待更新结果集
			resultMap.put(bean.getLineId()+"-"+bean.getStationName(), bean);
			//更新内置缓存
			cacheMap.put(bean.getLineId()+"-"+bean.getStationName(), bean);
		}
		return resultMap;
	}

}
